<template>

    <el-dialog
        :visible.sync="dialogVisible"
        title="修改密码"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        width="400px"
        append-to-body
    >

        <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="新密码" prop="password">
                <el-input v-model="formData.password" type="password"/>
            </el-form-item>
            <el-form-item label="再次输入" prop="password2">
                <el-input v-model="formData.password2" type="password"/>
            </el-form-item>
            <el-form-item>
                <el-popconfirm :title="'确定修改吗？'" @onConfirm="submitForm()">
                    <el-button slot="reference" type="primary">确定</el-button>
                </el-popconfirm>
            </el-form-item>
        </el-form>

    </el-dialog>
</template>

<script>
import {AdminApi} from '@/api/system/admin'

export default {
    name: 'UpdatePassword',
    data() {
        return {
            formData: {
                password: '',
                password2: ''
            },
            rules: {
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                    {min: 8, max: 20, message: '长度在 8 到 20 个字符', trigger: 'blur'}
                ],
                password2: [
                    {required: true, message: '请再次输入密码', trigger: 'blur'}
                ]
            },
            dialogVisible: false
        }
    },
    methods: {
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.formData.password !== this.formData.password2) {
                        this.$alert('两次密码输入不一致')
                        return false
                    }
                    const data = {
                        password: this.formData.password
                    }
                    AdminApi.updatePassword(data).then(() => {
                        this.dialogVisible = false
                    })
                }
            })
        },
        showUpdatePassword() {
            this.dialogVisible = true
            if (this.$refs['form'] !== undefined) {
                this.$refs['form'].resetFields()
            }
        }
    }
}
</script>
